//package cn.steel.service.impl;
//
///**
// * @author: zhaoyuhan
// * @date: 2025/4/28
// * @description: 实现类定义
// */
//import cn.steel.dto.ReceiptDto;
//import cn.steel.entity.Receipt;
//import cn.steel.mapper.ReceiptMapper;
//import cn.steel.service.ReceiptService;
//import cn.steel.vo.ReceiptVo;
//import org.apache.logging.log4j.LogManager;
//import org.apache.logging.log4j.Logger;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import java.util.Date;
//import java.util.List;
//@Service
//public class ReceiptServiceImpl implements ReceiptService {
//
//    @Autowired
//    private ReceiptMapper receiptMapper;
//
//    private static final Logger log = LogManager.getLogger(OrderServiceImpl.class);
//    @Override
//    @Transactional
//    public Long saveReceipt(Long userId, ReceiptDto receiptDto) {
//        Receipt receipt = new Receipt();
//        BeanUtils.copyProperties(receiptDto, receipt);
//        receipt.setUserId(userId);
//        receipt.setCreateTime(new Date());
//        receipt.setUpdateTime(new Date());
//
//        if (receiptDto.getIsDefault() != null && receiptDto.getIsDefault() == 1) {
//            receiptMapper.clearDefault(userId);
//        }
//
//        receiptMapper.insert(receipt);
//        return receipt.getId();
//    }
//
//    @Override
//    public List<ReceiptVo> getReceiptList(Long userId) {
//        return receiptMapper.selectByUserId(userId);
//    }
//
//    @Override
//    public ReceiptVo getReceiptDetail(Long id, Long userId) {
//        return receiptMapper.selectById(id);
//    }
//
//@Override
//@Transactional
//public boolean setDefaultReceipt(Long id, Long userId) {
//    log.info("清除旧默认地址 userId={}", userId);
//    receiptMapper.clearDefault(userId);
//
//    log.info("设置新的默认地址 id={}, userId={}", id, userId);
//    int result = receiptMapper.setDefault(id, userId);
//    log.info("受影响行数: {}", result);
//
//    return result > 0;
//}
//
//
//
//}
package cn.steel.service.impl;

/**
 * @author: zhaoyuhan
 * @date: 2025/4/28
 * @description: 收货信息实现类定义
 */

import cn.steel.domain.dto.ReceiptDto;
import cn.steel.domain.entity.Receipt;
import cn.steel.domain.vo.ReceiptVo;
import cn.steel.mapper.ReceiptMapper;
import cn.steel.service.ReceiptService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;


@Service
public class ReceiptServiceImpl implements ReceiptService {

    @Autowired
    private ReceiptMapper receiptMapper;

    private static final Logger log = LogManager.getLogger(ReceiptServiceImpl.class);

    @Override
    @Transactional
    public Long saveReceipt(Long userId, ReceiptDto receiptDto) {
        Receipt receipt = new Receipt();
        BeanUtils.copyProperties(receiptDto, receipt);
        receipt.setUserId(userId);
        receipt.setCreateTime(new Date());
        receipt.setUpdateTime(new Date());

        if (receiptDto.getIsDefault() != null && receiptDto.getIsDefault() == 1) {
            log.info("Clearing existing default receipts for userId={}", userId);
            receiptMapper.clearDefault(userId);
        }

        log.info("Inserting new receipt for userId={}", userId);
        receiptMapper.insert(receipt);
        return receipt.getId();
    }

    @Override
    public List<ReceiptVo> getReceiptList(Long userId) {
        return receiptMapper.selectByUserId(userId);
    }

    @Override
    public ReceiptVo getReceiptDetail(Long id, Long userId) {
        return receiptMapper.selectById(id);
    }

    @Override
    @Transactional
    public boolean setDefaultReceipt(Long id, Long userId) {
        log.info("Clearing old default address for userId={}", userId);
        int cleared = receiptMapper.clearDefault(userId);
        log.info("Cleared {} rows of old default addresses", cleared);

        log.info("Setting new default address id={}, userId={}", id, userId);
        int result = receiptMapper.setDefault(id, userId);
        log.info("Set default affected rows: {}", result);

        return result > 0;
    }

    @Override
    public boolean deleteReceipt(Long id, Long userId) {
        try {
            int result = receiptMapper.deleteByIdAndUserId(id, userId);
            return result > 0;
        } catch (Exception e) {
            log.error("删除收货地址失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateReceipt(Long userId, Long id, ReceiptDto receiptDto) {
        // 检查地址是否已存在（排除当前地址）
        if (receiptMapper.countSameAddress(userId, receiptDto.getContactName(),
                receiptDto.getContactPhone(), receiptDto.getDeliveryAddress(), id) > 0) {
            throw new RuntimeException("相同的收货地址已存在");
        }

        Receipt receipt = new Receipt();
        BeanUtils.copyProperties(receiptDto, receipt);
        receipt.setId(id);
        receipt.setUserId(userId);
        receipt.setUpdateTime(new Date());

        if (receiptDto.getIsDefault() != null && receiptDto.getIsDefault() == 1) {
            receiptMapper.clearDefault(userId);
        }

        return receiptMapper.update(receipt) > 0;
    }

    @Override
    public boolean isAddressExists(Long userId, String contactName, String contactPhone, String deliveryAddress) {
        return receiptMapper.countSameAddress(userId, contactName, contactPhone, deliveryAddress, null) > 0;
    }

    @Override
    public ReceiptVo getDefaultReceipt(Long userId) {
        // 根据业务逻辑实现获取默认收货地址的功能
        // 这里假设通过某个mapper或者其他方式获取，示例代码如下
        return receiptMapper.getDefaultReceiptByUserId(userId);
    }
}